import React, { useState, useCallback } from 'react';
import { TextInput } from './components/TextInput';
import { MoodDisplay } from './components/MoodDisplay';
import { ImageDisplay } from './components/ImageDisplay';
import { ErrorDisplay } from './components/ErrorDisplay';
import { analyzeMood, generateImage } from './services/modelscope';
import type { AppState } from './types';
import './styles/App.css';

const App: React.FC = () => {
  const [state, setState] = useState<AppState>({
    inputText: '',
    isAnalyzing: false,
    isGeneratingImage: false,
    currentMood: null,
    generatedImage: null,
    error: null,
    history: []
  });

  const handleTextChange = useCallback((text: string) => {
    setState(prev => ({ ...prev, inputText: text }));
  }, []);

  const handleSubmit = useCallback(async () => {
    if (!state.inputText.trim() || state.isAnalyzing) return;

    // 重置状态
    setState(prev => ({
      ...prev,
      isAnalyzing: true,
      isGeneratingImage: false,
      currentMood: null,
      generatedImage: null,
      error: null
    }));

    try {
      // 第一步：分析情绪
      const mood = await analyzeMood(state.inputText);
      setState(prev => ({
        ...prev,
        isAnalyzing: false,
        isGeneratingImage: true,
        currentMood: mood
      }));

      // 第二步：生成图片
      const image = await generateImage({
        text: state.inputText,
        mood,
        style: '水彩画风格'
      });

      setState(prev => ({
        ...prev,
        isGeneratingImage: false,
        generatedImage: image,
        history: [{
          id: Date.now().toString(),
          text: prev.inputText,
          mood,
          image,
          timestamp: Date.now()
        }, ...prev.history.slice(0, 9)] // 只保留最近10条记录
      }));

    } catch (error) {
      setState(prev => ({
        ...prev,
        isAnalyzing: false,
        isGeneratingImage: false,
        error: error instanceof Error ? error.message : '处理失败，请稍后重试'
      }));
    }
  }, [state.inputText, state.isAnalyzing]);

  const handleErrorDismiss = useCallback(() => {
    setState(prev => ({ ...prev, error: null }));
  }, []);

  const isLoading = state.isAnalyzing || state.isGeneratingImage;

  return (
    <div className="app">
      <header className="app-header">
        <h1 className="app-title">墨韵情境</h1>
        <p className="app-subtitle">用文字触动情感，让AI为你绘制心境</p>
      </header>

      <main className="app-main">
        <ErrorDisplay 
          error={state.error} 
          onDismiss={handleErrorDismiss} 
        />

        <section className="input-section">
          <TextInput
            value={state.inputText}
            onChange={handleTextChange}
            onSubmit={handleSubmit}
            isLoading={isLoading}
          />
        </section>

        <div className="results-container">
          <section className="mood-section">
            <h2 className="section-title">情绪分析</h2>
            <MoodDisplay 
              mood={state.currentMood} 
              isLoading={state.isAnalyzing} 
            />
          </section>

          <section className="image-section">
            <h2 className="section-title">情境图片</h2>
            <ImageDisplay 
              image={state.generatedImage} 
              isLoading={state.isGeneratingImage} 
            />
          </section>
        </div>

        {state.history.length > 0 && (
          <section className="history-section">
            <h2 className="section-title">历史记录</h2>
            <div className="history-grid">
              {state.history.slice(0, 6).map((item) => (
                <div key={item.id} className="history-item">
                  <div className="history-image">
                    <img src={item.image.url} alt="Historical mood" />
                  </div>
                  <div className="history-info">
                    <p className="history-text">{item.text.slice(0, 50)}...</p>
                    <span className="history-emotion">
                      {item.mood.description}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </section>
        )}
      </main>

      <footer className="app-footer">
        <p>基于魔搭社区AI模型 · 让每一段文字都有专属的视觉呈现</p>
      </footer>
    </div>
  );
};

export default App;